package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbMenuMapper;
import com.bwie.pojo.TbMenu;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.Result;
import com.bwie.vo.LoginForm;
import com.bwie.vo.PageVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Lenovo
 * @description 针对表【tb_user】的数据库操作Service实现
 * @createDate 2025-05-21 16:31:21
 */
@Service
@Slf4j
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
        implements TbUserService {
    @Autowired
    TbUserMapper tbUserMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    HttpServletRequest request;
    @Autowired
    TbMenuMapper tbMenuMapper;
    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Override
    public Result login(LoginForm loginForm) {

        TbUser tbUser = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserName, loginForm.getUserName())
        );

        if (tbUser == null) {
            return Result.error().setCode(500).setMsg("用户不存在");
        }

        String pass = DigestUtil.md5Hex(loginForm.getUserPass());
        log.info("加密后的密码：" + pass);
        if (!pass.equals(tbUser.getUserPass())) {
            return Result.error().setCode(500).setMsg("密码错误");
        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .claim("nickName", tbUser.getNickName())
                .compact();
        String tokenKey = "token-" + tbUser.getUserId();

        redisTemplate.opsForValue().set(tokenKey, token, 60, TimeUnit.MINUTES);

        tbUser.setUserPass(null);
        tbUser.setToken(token);

        return Result.ok().setCode(200).setData(tbUser);
    }

    @Override
    public Result getMenuList() {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error().setCode(500).setMsg("请先登录");
        }
        Integer userId = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userId", Integer.class);

        List<TbMenu> tbMenuList = tbMenuMapper.getMenuList(userId);

        List<Tree<String>> treeList = TreeUtil.build(tbMenuList, "0", (menu, tree) -> {
            tree.setId(menu.getMenuId() + "");
            tree.setName(menu.getMenuName());
            tree.setParentId(menu.getMenuPid() + "");
            tree.putExtra("path", menu.getMenuPath());
        });
        return Result.ok().setData(treeList);
    }

    @Override
    public Result getUserPage(PageVo pageVo) {
        Page<TbUser> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());
        LambdaQueryWrapper<TbUser> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(pageVo.getKeyWord())) {
            wrapper.like(TbUser::getUserName, pageVo.getKeyWord())
                    .or()
                    .like(TbUser::getNickName, pageVo.getKeyWord())
                    .or()
                    .like(TbUser::getUserMobile, pageVo.getKeyWord())
                    .or()
                    .like(TbUser::getUserEmail, pageVo.getKeyWord());
        }
        if (ObjectUtils.isNotEmpty(pageVo.getTypeId())) {
            wrapper.eq(TbUser::getGender, pageVo.getTypeId());
        }
        if (StringUtils.isNotEmpty(pageVo.getBeginTime())) {
            wrapper.ge(TbUser::getCreateTime, pageVo.getBeginTime());
        }
        if (StringUtils.isNotEmpty(pageVo.getEndTime())) {
            wrapper.le(TbUser::getCreateTime, pageVo.getEndTime());
        }

        Page<TbUser> tbUserPage = tbUserMapper.selectPage(page, wrapper);
        return Result.ok().setData(tbUserPage);
    }

    @Override
    public Result uploadImage(MultipartFile file) {
        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());

            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            if (storePath == null) {
                return Result.error().setMsg("上传失败");
            }
            String url = "http://192.168.80.192:8888/" + storePath.getFullPath();
            return Result.ok().setData(url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().setMsg("上传失败");
        }

    }

    @Override
    public Result updateUser(TbUser tbUser) {
        TbUser user = tbUserMapper.selectById(tbUser.getUserId());
        if(user == null){
            return Result.error().setMsg("商户不存在");
        }

        tbUserMapper.updateById(tbUser);
        return Result.ok().setMsg("修改成功");
    }

    @Override
    public Result deleteByUserId(Integer id) {
        TbUser tbUser = tbUserMapper.selectById(id);
        if(tbUser == null){
            return Result.error().setMsg("商户不存在");
        }

        tbUserMapper.deleteById(id);
        return Result.ok().setMsg("删除成功");
    }

    @Override
    public Result deleteBatch(List<TbUser> ids) {
        if(ids==null||ids.size()==0){
            return Result.error().setMsg("请选择要删除的数据");
        }

        for (TbUser id : ids) {
            tbUserMapper.deleteById(id);
        }
        return Result.ok().setMsg("删除成功");
    }

    @Override
    public Result checkUser(TbUser tbUser) {
        if(tbUser.getUserStatus()==2){
            if(StringUtils.isEmpty(tbUser.getReason())){
                return Result.error().setMsg("请输入审核备注");
            }
        }
        TbUser user = tbUserMapper.selectOne(
                new LambdaQueryWrapper<TbUser>().eq(TbUser::getUserName, tbUser.getUserName())
        );

        user.setUserStatus(tbUser.getUserStatus());
        user.setReason(tbUser.getReason());

        tbUserMapper.updateById(user);
        return Result.ok();
    }
}




